import hashlib
import uuid
import json
import datetime
import time
import os
import base64
import random
from Lib.AlchemyJsonEncoder import *
import os
import platform
import psutil

# 判断当前系统是linux还是windows
system_name = platform.system()


"""通用工具类"""
class Utils(object):
    def __init__(self, *args, **kwargs):
        return super().__init__(*args, **kwargs)

    #MD5加密
    def MD5(str):
        # 创建md5对象
        hl = hashlib.md5()
        hl.update(str.encode(encoding='utf-8'))
        return hl.hexdigest()

    #获取唯一识别码
    def UUID():
        return uuid.uuid1()

    #获取MAC地址
    def getMacAddress():
        mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
        return ":".join([mac[e:e+2] for e in range(0,11,2)])

    #将sqlAlchemy Sql执行数据对象列表转换为实体列表
    def mysqlTable2Model(dataList):
        mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
        return [dict(zip(result.keys(), result.values())) for result in dataList]

    #生成统一格式接口数据
    @staticmethod
    def ResultData(status,message,data=""):
        return json.dumps({"status":status,"message":message,"data":data},cls=AlchemyEncoder)

    #按时间生成随机文件名
    def getFileName():
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")#生成当前的时间
        randomNum = random.randint(0,100)#生成随机数n,其中0<=n<=100
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum)
        uniqueNum = str(nowTime) + str(randomNum)
        return uniqueNum

    #获取当前插入U盘路径
    @staticmethod
    def getUDiskPath():
        if system_name == 'Windows':
            disk_list = psutil.disk_partitions()
            # 获取U盘路径
            u_path = [disk.device for disk in disk_list if disk.opts == 'rw,removable']
            if u_path:
                return u_path[0]
        elif system_name == 'Linux':
            import pyudev
            context = pyudev.Context()
            removable = [device for device in context.list_devices(subsystem='block', DEVTYPE='disk') if device.attributes.asstring('removable') == "1"]
            for device in removable:
              partitions = [device.device_node for device in context.list_devices(subsystem='block', DEVTYPE='partition', parent=device)]
              #print("All removable partitions: {}".format(",
              #".join(partitions)))
              #print("Mounted removable partitions:")

              for p in psutil.disk_partitions():
                  if p.device in partitions:
                      return p.mountpoint
        return ""
    #创建文件夹
    def mkdir(path):
        folder = os.path.exists(path)
        if not folder:
            os.makedirs(path)

    #获取指定目录下的所有文件
    def getFileList(dir,startTime,endTime):
        _files = []
        list = os.listdir(dir) #列出文件夹下所有的目录与文件
        #startTime=int(time.mktime((datetime.datetime.strptime("2018-9-18 12:00:00","%Y-%m-%d %H:%M:%S")).timetuple()))
        #startTime=int(datetime.datetime.strptime("2018-9-18 16:00:00","%Y-%m-%d %H:%M:%S").strftime("%Y%m%d%H%M%S"))
        #print(startTime)
        print([x for x in list if  int(x.replace('.avi','')) > int(startTime.strftime("%Y%m%d%H%M%S")) and int(x.replace('.avi',''))<int(endTime.strftime("%Y%m%d%H%M%S"))])
        for i in range(0,len(list)):
               path = os.path.join(dir,list[i])
               if os.path.isdir(path):
                  _files.extend(list_all_files(path))
               if os.path.isfile(path):
                  _files.append(list[i])
        return _files

    # 生成统一格式接口数据
    @staticmethod
    def resultAlchemyData(data):
        return json.dumps(data, cls=AlchemyEncoder)

    # 将图片转化为base64的字节
    @staticmethod
    def change_img_as_base64(img_name):
        with open(img_name, 'rb') as f:
            return base64.b64encode(f.read())

    # 将base64转化为图片格式
    @staticmethod
    def change_base64_as_img(bs64):
        img_data = base64.b64decode(bs64)
        img_path = str(Utils.UUID()) + '.jpg'
        with open(img_path, 'wb') as f:
            f.write(img_data)
        return img_path
